package com.tanhua.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.Analysis;
import com.tanhua.model.vo.UsersDataVo;
import org.apache.commons.lang.time.DateUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DashboardService {
    @Autowired
    private AnalysisMapper analysisMapper;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private LogMapper logMapper;
    /**
     * 操作类型,
     * 0101为登录，0102为注册，
     * 0201为发动态，0202为浏览动态，0203为动态点赞，0204为动态喜欢，0205为评论，0206为动态取消点赞，0207为动态取消喜欢，
     * 0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
     */

    /**
     * 查询概要统计信息
     */
    public Map summary() {
        //根据今日查询
        QueryWrapper qw = new QueryWrapper();
        qw.eq("record_date", getDate(0));
        Analysis analysis = analysisMapper.selectOne(qw);
        if (analysis==null){
            analysis=new Analysis();
            analysis.setNumActive(0);
            analysis.setNumLogin(0);
            analysis.setNumRegistered(0);
            analysis.setNumRetention1d(0);
        }
        System.out.println(analysis.toString());
        /**
         * 查询累计用户数
         */
        Integer cumulativeUsers = logMapper.findAll();
        /**
         * 查询过去7天活跃用户
         */
        String logTime = getDate(-7);
        Integer activePassWeek = logMapper.queryByGtLogTime(logTime);
        System.out.println(activePassWeek.toString());
        /**
         * 查询过去30天的活跃用户
         */
        logTime = getDate(-30);
        Integer activePassMonth = logMapper.queryByGtLogTime(logTime);
        /**
         *查询今日新增用户
         */
        Integer newUsersToday = analysis.getNumRegistered();
        /**
         * 今日新增用户涨跌率，单位百分数，正数为涨，负数为跌
         *   (今日-昨日)/昨日=涨跌率;
         */
        //获取昨日新增用户 0102注册
        Integer newYesterdayUser = logMapper.queryByTypeAndLogTime("0102", getDate(-1));
        //设置涨跌率
        int newUsersTodayRate = 0;
        //判断昨日是否为空
        if (newYesterdayUser != null && newYesterdayUser != 0) {
            // (今日-昨日)/昨日=涨跌率;
            newUsersTodayRate = (newUsersToday - newYesterdayUser) / newYesterdayUser;
        }
        /**
         * 今日登录次数涨跌率，单位百分数，正数为涨，负数为跌
         * (今日-昨日)/昨日=涨跌率;
         */
        //获取今日登录次数
        Integer loginTimesToday = analysis.getNumLogin();
        //获取昨日登录次数
        Integer loginTimesYesterday = logMapper.queryByTypeAndLogTime("0101", getDate(-1));
        int loginTimesTodayRate = 0;
        if (loginTimesYesterday != null && loginTimesYesterday != 0) {
            // (今日-昨日)/昨日=涨跌率;
            loginTimesTodayRate = (loginTimesToday - loginTimesYesterday) / loginTimesYesterday;
        }

        /**
         * 今日活跃用户涨跌率，单位百分数，正数为涨，负数为跌
         */
        //获取今日活跃用户
        Integer activeUsersToday = analysis.getNumActive();
        //获取昨日活跃用户---登录 点赞之类的都算活跃 所以直接用日期查询
        Integer numActiveYesterday = logMapper.queryByLogTime(getDate(-1));
        //涨跌率
        int activeUsersTodayRate = 0;
        if (numActiveYesterday != null && numActiveYesterday != 0) {
            // (今日-昨日)/昨日=涨跌率;
            activeUsersTodayRate = (activeUsersToday - numActiveYesterday) / numActiveYesterday;
        }


        //把各个数据封装到map集合中
        Map map = new HashMap();
        map.put("cumulativeUsers", cumulativeUsers);
        map.put("activePassMonth", activePassMonth);
        map.put("activePassWeek", activePassWeek);
        map.put("newUsersToday", newUsersToday);
        map.put("newUsersTodayRate", newUsersTodayRate);
        map.put("loginTimesToday", loginTimesToday);
        map.put("loginTimesTodayRate", loginTimesTodayRate);
        map.put("activeUsersToday", activeUsersToday);
        map.put("activeUsersTodayRate", activeUsersTodayRate);
        return map;
    }

    /**
     * 计算日记方法
     */
    public String getDate(int i) {
        Date now = new Date();
        Date date = DateUtils.addDays(now, i);
        return new SimpleDateFormat("yyyy-MM-dd").format(date);
    }
    public String getDate(String date,int i){
        SimpleDateFormat simpleDateFormat = null;
        Date date1 = null;
        try {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date now=simpleDateFormat.parse(date);
            date1 = DateUtils.addDays(now, i);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return simpleDateFormat.format(date1);
    }

    /**
     * 新增、活跃用户、次日留存率
     * * 0101为登录，0102为注册，
     * * 0201为发动态，0202为浏览动态，0203为动态点赞，0204为动态喜欢，0205为评论，0206为动态取消点赞，0207为动态取消喜欢，
     * * 0301为发小视频，0302为小视频点赞，0303为小视频取消点赞，0304为小视频评论
     *
     * @param sd   开始
     * @param type 类型
     * @param ed   结束
     * @return
     */
    public UsersDataVo users(String sd, String type, String ed) {
        UsersDataVo vo = new UsersDataVo();
        String types;
        switch(type){
            //新增
            case "101":
                types = "num_registered as amount";
                vo = getUserDataVo(sd, ed,types);
                break;

            //活跃用户
            case "102":
                types = "num_active as amount";
                vo = getUserDataVo(sd, ed,types);
                break;

            //次日留存率
            case "103":
                types = "num_retention1d as amount";
                vo = getUserDataVo(sd, ed,types);
                break;

        }

        return vo;
    }

    /**
     * 获取今年去年的数据
     */
    private UsersDataVo getUserDataVo(String sd,String ed,String types){
        //转化开始 结束 时间
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        sd=dateFormat.format(new Date(Long.valueOf(sd)));
        ed=dateFormat.format(new Date(Long.valueOf(ed)));
        //设置去年今年
        List<Map<String, Object>> lastYear;//去年
        List<Map<String, Object>> thisYear;//今年
        UsersDataVo vo=new UsersDataVo();

        //获取今年
        QueryWrapper<Analysis> qw=new QueryWrapper();
        qw.select("record_date as title", types).le("record_date", ed).ge("record_date",sd);
        thisYear=analysisMapper.selectMaps(qw);
        //前年
        sd=getDate(sd,-365);
        ed=getDate(ed,-365);
        QueryWrapper<Analysis> qw1=new QueryWrapper();
        qw1.select("record_date as title", types).le("record_date", ed).ge("record_date",sd);
        lastYear=analysisMapper.selectMaps(qw1);
        vo=new UsersDataVo(thisYear.toArray(), lastYear.toArray());
        return vo;
    }



}